package web.servlet.list.dao;


import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import web.servlet.list.domin.User;
import web.servlet.list.utils.JDBCUtils;

import java.util.List;

/**
 * @Author Administrator
 * @Date 2020/6/12 9:40
 **/
public class UserDaoImpl implements UserDao {
    JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
    String sql = " ";

    @Override
    public List<User> findAll() {
        try {
            sql = "select * from user2";
            List<User> user = template.query(sql, new BeanPropertyRowMapper<User>(User.class));
            return user;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }

    }

    @Override
    public int insert(User user) {
        User u= selectByName(user.getName());
        if (u == null) {
            sql = "insert into user2(name,gender,age,address,qq,email) values(?,?,?,?,?,?)";
            int i = template.update(sql, user.getName(), user.getGender(), user.getAge(), user.getAddress(),user.getQq(), user.getEmail());
            return i;
        } else {
            return -1;
        }
    }

    @Override
    public User selectByName(String name) {
        try {
            sql = "select * from user2 where name=?";
            User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), name);
            return user;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

    @Override
    public int update(int id, User user) {
        sql = "update user2 set name=?,gender=?,age=?,address=?,qq=?,email=? where id=?";
        int i = template.update(sql, user.getName(), user.getGender(), user.getAge(), user.getAddress(),user.getQq(), user.getEmail(), id);
        return i;
    }

    @Override
    public int delete(int id) {
        sql = "delete from user2 where id=?";
        int i = template.update(sql, id);
        return i;
    }

    @Override
    public User findById(int id) {
        try {
            sql = "select * from user2 where id=?";
            User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class),id);
            return user;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }

    }
}
